from flask import Flask, request, current_app, jsonify
from elasticsearch5 import Elasticsearch

app = Flask(__name__)
class Config(object):
    # elasticsearch集群服务器的地址
    ES = [
        '127.0.0.1:9200'
    ]
app.config.from_object(Config)

# 创建elasticsearch客户端
app.es = Elasticsearch(
    app.config.get('ES'),
    # 启动前嗅探es集群服务器
    sniff_on_start=True,
    # es集群服务器结点连接异常时是否刷新es结点信息
    sniff_on_connection_fail=True,
    # 每60秒刷新结点信息
    sniffer_timeout=60
)

@app.route('/')
def index():
    q = request.args.get('q')
    query = {
        'query': {
            'bool': {
               'must': [
                   {'match': {'_all': q}}
               ],
                'filter': [
                    {'term': {'status': 2}}
                ]
            }
        }
    }
    ret = current_app.es.search(index='articles', doc_type='article', body=query)
    return jsonify(ret)

if __name__ == '__main__':
    app.run(debug=True, host='192.168.226.129')